var mongoose = require("mongoose");
var Upload = require("../modules/upload.module");
var multer = require("multer");
var path = require('path');

exports.filedata = function(req, res, next) {
    var storage = multer.diskStorage({
        destination: function(req, file, cb) {
            cb(null, "uploads/");
        },
        filename: function(req, file, cb) {
            cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname));
        }
    });
    var upload = multer({ storage: storage }).single("avatar");
    upload(req, res, function(err) {
        // console.log(req.file)
        var uploads = new Upload(req.file);
        uploads.save(function(err, data) {
            if (err) {
                console.log(err);
            } else {
                res.json(data);
            }
        });
    })
}

exports.update = function(req, res, next) {
    const id = req.params.id;

    User.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
        res.json(data);
    });
};

exports.remove = function(req, res, next) {
    const id = req.params.id;

    User.findByIdAndRemove(id, function(err, data) {
        res.json({ message: "delete ok" });
    });
};
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var limit = req.body.limit ? req.body.limit : 3;
    var queryCondition = {};
    if (req.body.name && req.body.name.trim().length) {
        name = req.body.name;
        queryCondition = {
            name: new RegExp(name, "i")
        };
    }

    if (req.body._id) {
        _id = req.body._id;
        queryCondition = {
            _id: _id
        };
    }

    User.paginate(queryCondition, { page: page, limit: limit }, function(
        err,
        results
    ) {
        res.json(results);
    });
};